package com.example.mongodb.repository;

import com.example.mongodb.domain.Student;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author HJW
 */
@Component
public class StudentRepository {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 查询学生列表
     * @param query
     * @return
     */
    public List<Student> selectList(Query query){
        return mongoTemplate.find(query,Student.class);
    }

    /**
     * 保存一条学生信息
     * @param student
     */
    public void save(Student student){
        mongoTemplate.save(student);
    }

    /**
     * 更新一条学生信息
     * @param query
     * @param update
     */
    public void update(Query query, Update update){
        mongoTemplate.updateMulti(query, update, Student.class);
    }

    /**
     * 删除学生信息
     * @param query
     */
    public void delete(Query query){
        mongoTemplate.remove(query,Student.class);
    }

    /**
     * 统计学生数量
     * @param query
     * @return
     */
    public long count(Query query){
        return mongoTemplate.count(query, Student.class);
    }

    /**
     * 分页查询学生列表
     * @param query
     * @param pageNum
     * @param pageSize
     * @return
     */
    public List<Student> selectListByPage(Query query, int pageNum, int pageSize){
        query.skip((long) (pageNum - 1) * pageSize).limit(pageSize);
        return mongoTemplate.find(query, Student.class);
    }

    /**
     * 根据最小值和最大值查询学生年龄范围
     * @param minAge
     * @param maxAge
     * @return
     */
    public List<Student> selectListByAgeRange(int minAge, int maxAge){
        Query query = new Query();
        query.addCriteria(Criteria.where("age").gte(minAge).lte(maxAge));
        return mongoTemplate.find(query, Student.class);
    }
}
